using System;
using System.Collections.Generic;
using System.Text;

using System.Management.Automation;

namespace Microsoft.PowerShell.CmdletManagement
{
    [Cmdlet(VerbsCommon.Get, "PsSpecProject")]
    public class GetPsSpecProjectCommand : Cmdlet
    {
        [Parameter(Mandatory = false, Position = 0, ValueFromPipelineByPropertyName = true)]
        [ValidateLength(1, 50)]
        public String Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }
        private string _name = "*";

        [Parameter(Mandatory = false, Position = 1)]
        public String ServiceUri
        {
            get
            {
                return _serviceUri;
            }
            set
            {
                _serviceUri = value;
            }
        }
        private string _serviceUri = PsSpecCmdletUtils.Constants.ServiceUri;


        protected override void ProcessRecord()
        {
            if (! PsSpecCmdletUtils.IsValidWildcardedProjectName(Name))
            {
                WriteError(new ErrorRecord(
                    new Exception(resources.InvalidProjectName),
                    "INVALID_PROJECT_NAME",
                    ErrorCategory.InvalidArgument, Name));
                return;
            }

            PsSpecCmdletService.PsSpecProject[] projects = null;

            PsSpecCmdletService.CmdletService service =
                new PsSpecCmdletService.CmdletService();
            service.Url = ServiceUri;

            service.UseDefaultCredentials = true;

            string convertedName = PsSpecCmdletUtils.ConvertWildcardToSqlWildcard(Name);
            projects = service.GetProject(convertedName);

            bool projectFound = false;
            foreach (PsSpecCmdletService.PsSpecProject project in projects)
            {
                projectFound = true;
                WriteObject(new PsSpecProject(project.Id, project.Name, project.Description, project.Owner));
            }

            // Generate an error if no projects found, and no globbing was done
            if ((!projectFound) && String.Equals(Name, convertedName, StringComparison.InvariantCultureIgnoreCase))
            {
                string message = String.Format(resources.ProjectNotFound, Name);
                WriteError(new ErrorRecord(
                    new Exception(message), 
                    "PROJECT_NOT_FOUND",
                    ErrorCategory.ObjectNotFound,
                    Name));
            }
        }
    }
}